
#include "utils.h"
#include <QJsonDocument>
#include <QNetworkReply>
#include <QJsonObject>
extern QString kNumPlaceholder ="NNNNNN";
extern QString kStringPlaceholder = "XXXXXX";
extern QString kSplitChar = "_";
extern size_t kPinyinKeyMaxLength=20;

QString generatePinyin(QString full)
{

    auto begin = full.begin();

    //去除开头不是字母的字符，因为变量要以字母开头
    while (begin != full.cend())
    {
        if (!begin->isLetter())
        {
            begin = full.erase(begin, begin + 1);
        }
        else
        {
            break;
        }
    }
    //去除特殊字符，只保留字母和数字
    begin = full.begin();
    while (begin != full.cend())
    {
        if (!begin->isLetterOrNumber())
        {
            begin = full.erase(begin, begin + 1);
            continue;
        }
        else
        {
            ++begin;
        }
    }
    return full;
}

void requestPinYin(QNetworkAccessManager *network,const QString &zh,std::function<void(const QString &pinyin)> callback,std::function<void(const QString &errorMessage)> errCallback) {
    QNetworkRequest req;
    req.setUrl(QUrl("https://hn216.api.yesapi.cn/"));
    QJsonObject jobject({
                                {"app_key", "02B83C8A6278735694A0441860B15772"},
                                {"s","Ext.Pinyin.Convert"},
                                {"text", zh}
                        });
    QJsonDocument document(jobject);
//    req.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
    QNetworkReply *reply = network->post(req, document.toJson());
    network->connect(reply, &QNetworkReply::finished, [=]() {
        if(reply->error()!=QNetworkReply::NoError)
        {
            errCallback(reply->errorString());
            return;
        }
        QByteArray result =  reply->readAll();
        QJsonDocument j_result = QJsonDocument::fromJson(result);
        QJsonObject jo = j_result.object();
        if(jo["ret"].toInt()==200)
        {
            QJsonObject dataObject = jo["data"].toObject();
            if(dataObject["err_code"].toInt()==0)
            {
                QString pinyin = dataObject["pinyin"].toString();
                callback(pinyin);
            }
            else
            {
                errCallback(jo["err_msg"].toString());
            }
        }
        else
        {
            errCallback(jo["msg"].toString());
        }
    });
}
